package models

import (
	"fmt"
	"strings"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/astaxie/beego"
)

var bucket *oss.Bucket

func init() {
	client, err := oss.New(beego.AppConfig.String("AliyunEndPoint"), beego.AppConfig.String("AliyunAccessKeyID"), beego.AppConfig.String("AliyunAccessKeySecret"))
	if err != nil {
		beego.Error(err)
	}
	bucket, err = client.Bucket(beego.AppConfig.String("AliyunBucket"))
	if err != nil {
		beego.Error(err)
	}
}

//OssUpfile 上传图片
func OssUpfile(osspath, filepath string) (string, error) {
	err := bucket.PutObjectFromFile(osspath, filepath)
	if err != nil {
		beego.Error(err)
		return "", err
	}
	rtpath := fmt.Sprintf(`%v/%v`, beego.AppConfig.String("AliyunBucketDomin"), osspath)
	if strings.Index(filepath, "png") > -1 || strings.Index(filepath, "jpg") > -1 || strings.Index(filepath, "jpeg") > -1 {
		rtpath += "?x-oss-process=style/" + beego.AppConfig.String("AliyunBucketStyle")
	}
	return rtpath, nil
}
